import { Message, StorageData } from '../types/autoplayer';

const ALARM_NAME = 'autoplayer:alarm';

const handleError = (error: any, context: string) => {
  console.error(`[AP-background] Error in ${context}:`, error);
  chrome.storage.local.get('errors', ({ errors }) => {
    const newErrors = [ ...(errors || []).slice(-49), { error: error.message, context, timestamp: Date.now() }];
    chrome.storage.local.set({ errors: newErrors });
  });
};

chrome.runtime.onMessage.addListener((message: Message, sender, sendResponse) => {
  (async () => {
    try {
      if (message.type === 'start') {
        const { intervalSec } = message.payload as StorageData;
        await chrome.alarms.create(ALARM_NAME, {
          periodInMinutes: intervalSec / 60,
        });
        sendResponse({ status: 'started' });
      } else if (message.type === 'stop') {
        await chrome.alarms.clear(ALARM_NAME);
        sendResponse({ status: 'stopped' });
      } else if (message.type === 'error') {
        handleError(message.payload.error, message.payload.context);
        sendResponse({ status: 'error logged' });
      }
    } catch (e) {
      handleError(e, 'onMessage');
      sendResponse({ status: 'error' });
    }
  })();
  return true; // Indicates that the response is sent asynchronously
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === ALARM_NAME) {
    (async () => {
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab && tab.id) {
          await chrome.tabs.sendMessage(tab.id, { type: 'tick' });
        }
      } catch (e) {
        handleError(e, 'onAlarm');
      }
    })();
  }
});

chrome.commands.onCommand.addListener((command) => {
  (async () => {
    try {
      if (command === 'toggle-autoplayer') {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab && tab.id) {
          // We need to know the current status from content script to toggle
          // For now, let's just send a message and let content script handle it
          await chrome.tabs.sendMessage(tab.id, { type: 'toggle' });
        }
      }
    } catch (e) {
      handleError(e, 'onCommand');
    }
  })();
});

console.log('[AP-background] Service worker started.');